<?php

namespace app\store\controller\apps\bargain;

use app\store\controller\Controller;
use app\store\model\Comment as CommentModel;
use app\store\model\CommentImage;
use app\store\model\Goods;
use app\store\model\GoodsSku;
use app\store\model\Spec;
use app\store\model\SpecValue;
use app\store\model\User;

/**
 * 评论管理
 * Class Active
 * @package app\store\controller\apps\bargain
 */
class Comment extends Controller
{
    /**
     * 砍价活动列表
     * @param string $search
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($search = '')
    {
        $model = new CommentModel;
        $list = $model->getList();
        return $this->fetch('index', compact('list'));
    }

    /**
     * 删除评价
     * @param $comment_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($comment_id)
    {
        $model = CommentModel::get($comment_id);
        if (!$model->setDelete()) {
            return $this->renderError('删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 添加评价
     * @return array
     * @throws \think\exception\DbException
     */
    public function add()
    {
        // 评价详情
        if (!$this->request->isAjax()) {
            return $this->fetch('add');
        }
        $model = new CommentModel();
        // 更新记录
        $wxapp_id = 10001;
        $comment = array_merge($this->postData('comment'),
            [
                "create_time" => time(),
                "update_time" => time(),
                "wxapp_id" => $wxapp_id,
            ]
        );
        // 判断用户是否添加
        $userM = new  User();
        if ($comment['user_id']  ==  'default') {
            $count = $userM->count();
            do{
                $id = rand(1, $count);
                $user_id = $userM->where("user_id",$id)->value("user_id");
                if($user_id){
                    break;
                }
            }while(1);
            $comment['user_id'] = $user_id;
        }else{
            $user_id = $userM->where("user_id",$comment['user_id'])->value("user_id");
            if(empty($user_id)){
                return $this->renderError('用户不存在');
            }
        }

        // 判断商品是否添加
        $goodsM = new  Goods();
        if ($comment['goods_id'] ==  'default') {
            $count = $goodsM->count();
            do{
                $id = rand(1, $count);
                $good = $goodsM->where("goods_id",$id)->find();
                if($good){
                    break;
                }
            }while(1);
            $comment['goods_id'] = $id;
        }else{
            $goods = $goodsM->where("goods_id",$comment['goods_id'])->find();
            if(empty($goods)){
                return $this->renderError('商品不存在');
            }
        }
        // 获取商品规格
        $sku = new GoodsSku();
        $spec_sku = $sku->where("goods_id",$comment['goods_id'])->field("spec_sku_id")->select()->toArray();

        $sku_ids = [];
        if(!empty($spec_sku)){
            $sku_ids = array_column($spec_sku,'spec_sku_id');
        }
        $comment['attr'] = '';
        $index_spec = 0;
        if($sku_ids){
            $specM = new Spec();
            $spec = $specM->select()->toArray();
            $spec =  array_combine(array_column($spec,"spec_id"),$spec);

            $sku = $sku_ids[array_rand($sku_ids)];
            $a_sku = explode('_',$sku);
            $spec_valueM = new SpecValue();
            foreach ($a_sku as $sku_v) {
                if (!empty($sku_v)) {
                    $index_spec = 1;
                    $specV  = $spec_valueM->where("spec_value_id",$sku_v)->field("spec_value,spec_id")->find();
                    $comment['attr'] .= "{$spec[$specV['spec_id']]['spec_name']}:{$specV['spec_value']}; ";
                }
            }
        }
        if(empty($index_spec)){
            $comment['attr'] = '无规格';
        }

        // $comment 如果图片存在
        if(!empty($comment['images'])){
            $images = $comment['images'];
            $comment['is_picture']  = 1;
            unset($comment['images']);
        }

        $comment_id = $model->insertGetId($comment);
        if ($comment_id) {
            if(!empty($images)){
                $image_inster = [];
                $create_time = time();
                foreach ($images as $image_id){
                    $image_inster[] = [
                        "comment_id"=> $comment_id,
                        "image_id"=> $image_id,
                        "wxapp_id"=> $wxapp_id,
                        "create_time"=> $create_time,
                    ];
                }
                (new CommentImage())->saveAll($image_inster);
                isset($comment['images']) && $model->addCommentImages($comment['images']);
            }

            return $this->renderSuccess('添加成功', url('apps.bargain.comment/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 评价详情
     * @param $comment_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function detail($comment_id)
    {
        // 评价详情
        $model = CommentModel::detail($comment_id);
        $goodsM = new Goods();
        if (!$this->request->isAjax()) {
            if(!empty($model['attr'])){
                $goods = $goodsM->detail($model['goods_id']);
                $goods['content'] = '';
                $goods['goods_attr'] = $model['attr'];
                $goods['image']['file_path'] = $goods['image'][0]['file_path'] ?? '';
                $model['order_goods'] = $goods;
            }
            return $this->fetch('detail', compact('model'));
        }
        // 更新记录
        if ($model->edit($this->postData('comment'))) {
            return $this->renderSuccess('更新成功', url('apps.bargain.comment/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }
}